package serializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

import domain.SensorData;

public class JavaSerializer implements ISerializer {
	public SensorData decode(byte[] buf) {
		try (ByteArrayInputStream bis = new ByteArrayInputStream(buf);
				ObjectInput in = new ObjectInputStream(bis);) {
			Object obj = in.readObject();
			return (SensorData) obj;
		} catch (IOException | ClassNotFoundException e) {
			System.err
					.println("Error occured, while doing Java deserialization. Details: "
							+ e.getMessage());
		}
		return null;
	}

	public byte[] encode(SensorData obj) {
		try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
				ObjectOutput out = new ObjectOutputStream(bos);) {
			out.writeObject(obj);
			return bos.toByteArray();
		} catch (IOException e) {
			System.err
					.println("Error occured, while doing Java serialization. Details: "
							+ e.getMessage());
		}
		return null;
	}
}
